import react from '@vitejs/plugin-react-swc';
import * as path from 'path';
import unoCSS from 'unocss/vite';
import autoImport from 'unplugin-auto-import/vite';
import { defineConfig } from 'vite';
import svgr from 'vite-plugin-svgr';

import { colors } from './src/config/theme';

const { TYPE } = process.env;

/*
  parseTheme to $colors-red-200
*/
const parseTheme = () => {
  return Object.entries(colors)
    .flatMap(([key, color]) =>
      Object.entries(color).map(
        ([subKey, value]) => `$colors-${key}-${subKey}: ${value};`
      )
    )
    .join('');
};

// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
  const env = command === 'serve' ? 'development' : 'production';
  return {
    define: {
      'process.env.NODE_ENV': JSON.stringify(env),
      'import.meta.env.TYPE': JSON.stringify(TYPE)
    },
    base: command === 'serve' ? '' : '',
    server: {
      port: 8888,
      hmr: true,
      proxy: {
        '/proxy-api': {
          target: 'http://47.98.179.114:8080',
          secure: false,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/proxy-api/, '')
        }
      }
    },
    plugins: [
      autoImport({
        imports: ['react', 'react-router-dom', 'recoil', 'ahooks'],
        dts: './src/@types/auto-imports.d.ts'
      }),
      svgr({
        include: '**/*.svg'
      }),
      react({ jsxImportSource: '@emotion/react' }),
      unoCSS()
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@public': path.resolve(__dirname, 'public')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/mixins.scss" as * ;${parseTheme()}`
        }
      }
    }
  };
});
